<template>
  <div class="main">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="提交时间" prop="submitTimeList">
        <el-date-picker
          v-model="queryParams.submitTimeList"
          type="datetimerange"
          range-separator="至"
          format="yyyy-MM-dd HH:mm"
          value-format="yyyy-MM-dd HH:mm"
          start-placeholder="开始日期"
          size="small"
          @keyup.enter.native="handleQuery"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="提交人" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入提交人"
          clearable
          size="small"
          style="width:200px"
        />
      </el-form-item>
      <el-form-item label="流程状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable>
          <el-option
            v-for="item in dict.type.act_status"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="车辆类型" prop="carType">
        <el-select v-model="queryParams.carType" placeholder="请选择">
          <el-option
            v-for="dict in dict.type.car_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="归还日期" prop="busDateList">
        <el-date-picker
          v-model="queryParams.busDateList"
          type="daterange"
          range-separator="至"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          start-placeholder="开始日期"
          size="small"
          @keyup.enter.native="handleQuery"
          end-placeholder="结束日期"
          :picker-options="pickerOptionQuery"
          :default-time="['00:00:00', '23:59:59']"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="adminCarList"
      @selection-change="handleSelectionChange"
      :height="height"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="提交时间"
        align="center"
        prop="actBusinessStatus.createTime"
        width="180"
        sortable
      />
      <el-table-column
        label="提交人"
        align="center"
        prop="actBusinessStatus.createBy"
        width="180"
        sortable
      />
      <el-table-column label="开始时间" align="center" prop="busStartDate" width="180" sortable>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.busStartDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="busEndDate" width="180" sortable>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.busEndDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="时长(天)" align="center" prop="useCount" width="140" sortable />
      <el-table-column label="用车目的地" align="center" prop="useDistance" width="240" sortable />
      <el-table-column label="车辆类型" align="center" prop="carType" width="240" sortable>
        <template slot-scope="scope">
          <dict-tag :options="dict.type.car_type" :value="scope.row.carType" />
        </template>
      </el-table-column>
      <el-table-column
        label="流程状态"
        align="center"
        prop="actBusinessStatus.status"
        width="180"
        sortable
      >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.act_status" :value="scope.row.actBusinessStatus.status" />
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.actBusinessStatus.status==='draft'||scope.row.actBusinessStatus.status==='back'||scope.row.actBusinessStatus.status==='cancel'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-if="(scope.row.actBusinessStatus.status==='draft' || scope.row.actBusinessStatus.status==='cancel' || scope.row.actBusinessStatus.status==='back') && (scope.row.createBy === userId || userId === 'admin' || userId === 'sysadmin')"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button
            v-if="scope.row.actBusinessStatus.status==='waiting'"
            size="mini"
            type="text"
            icon="el-icon-back"
            @click="cancelProcessApply(scope.row)"
          >撤销</el-button>
          <el-button
            v-if="scope.row.actBusinessStatus.status!=='draft' || scope.row.actBusinessStatus.status==='cancel' || scope.row.actBusinessStatus.status==='back'"
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改公车使用申请对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="80%"
      append-to-body
      :before-close="cancel"
    >
      <el-tabs type="border-card">
        <el-tab-pane label="业务单据" v-loading="loading">
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="编号" prop="number">
              <el-input v-model="form.numberNum" disabled style="width: 280px;" />
            </el-form-item>
            <el-form-item label="用车事由" prop="busReason">
              <el-input
                :disabled="isdisabled"
                v-model="form.busReason"
                type="textarea"
                placeholder="请输入内容"
              />
            </el-form-item>
            <el-form-item label="开始时间" prop="busStartDate">
              <el-date-picker
                clearable
                style="width: 280px;"
                v-model="form.busStartDate"
                type="date"
                :disabled="isdisabled"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                @change="dateChanged"
                :picker-options="pickerOptionStart"
                placeholder="请选择开始时间"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间" prop="busEndDate">
              <el-date-picker
                clearable
                style="width: 280px;"
                v-model="form.busEndDate"
                type="date"
                :disabled="isdisabled"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                @change="dateChanged"
                :picker-options="pickerOptionEnd"
                placeholder="请选择结束时间"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="时长(天)" prop="useCount">
              <el-input
                style="width: 280px;"
                v-model="form.useCount"
                disabled
                placeholder="请输入用车时长"
              />
            </el-form-item>
            <el-form-item label="出发地点" prop="useDistance">
              <el-input
                :disabled="isdisabled"
                v-if="form.useDistance"
                v-model="form.useDistance"
                placeholder="请输入出发地点"
              >
                <i
                  v-if="!isdisabled"
                  slot="suffix"
                  class="el-icon-close"
                  @click="loadMap1()"
                  style="cursor: pointer;"
                ></i>
              </el-input>
              <el-cascader
                v-else
                style="width: 280px;"
                size="large"
                :options="options"
                v-model="form.useDistance"
                @change="handleChangePlace1"
              ></el-cascader>
            </el-form-item>

            <el-form-item label="车辆类型" prop="carType">
              <el-select
                style="width: 280px;"
                v-model="form.carType"
                placeholder="请选择"
                :disabled="isdisabled"
              >
                <el-option
                  v-for="dict in dict.type.car_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="附件">
              <file-upload v-model="form.attachment" :is-disabled="isdisabled" />
            </el-form-item>
          </el-form>
          <div class="dialog-footer" style="float:right" v-if="flag">
            <el-button :loading="buttonLoading" type="info" @click="submitForm('zancun')">暂存</el-button>
            <el-button :loading="buttonLoading" type="primary" @click="submitForm('submit')">提交</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-tab-pane>
        <!-- 审批历史 -->
        <el-tab-pane label="审批历史" v-if="processInstanceId">
          <history ref="historyRef" :processInstanceId="processInstanceId"></history>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <!-- 提交 -->
    <verify
      ref="verifyRef"
      @submitCallback="submitCallback"
      :taskId="taskId"
      :taskVariables="taskVariables"
      :sendMessage="sendMessage"
    ></verify>
  </div>
</template>
<script>
import {
  listAdminCar,
  getAdminCar,
  delAdminCar,
  addAdminCar,
  updateAdminCar,
  getProjectList
} from "@/api/oa/adminCar";
import processApi from "@/api/workflow/processInst";
import history from "@/components/Process/History";
import verify from "@/components/Process/Verify";
import { parseTime } from "@/utils/ruoyi";
import { CodeToText, provinceAndCityData } from "element-china-area-data";
import dayjs from "dayjs";
export default {
  name: "AdminCar",
  dicts: ["act_status", "car_type"],
  components: {
    history,
    verify
  },
  props: {},
  data() {
    return {
      componentName: "公车使用审批",
      height: `calc(100% - 88px)`,
      isdisabled: false,
      // 流程实例
      processInstanceId: "",
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 公车使用申请表格数据
      adminCarList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        submitTimeList: [],
        createBy: "",
        status: "",
        busReason: undefined,
        busStartDate: undefined,
        busEndDate: undefined,
        useCount: undefined,
        useDistance: undefined,
        carType: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        busReason: [
          { required: true, message: "用车事由不能为空", trigger: "blur" }
        ],
        busStartDate: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        busEndDate: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ],
        useCount: [
          { required: true, message: "用车时长不能为空", trigger: "blur" }
        ],
        useDistance: [
          { required: true, message: "用车目的地不能为空", trigger: "blur" }
        ],
        carType: [
          { required: true, message: "车辆类型不能为空", trigger: "change" }
        ]
      },
      taskVariables: {}, //流程变量
      taskId: undefined, //任务id
      flag: true,
      // 消息提醒
      sendMessage: {},
      processKey: "oa_admin_car",
      userId: "",
      isManager: false,
      deptId: "",
      pickerOptionQuery: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      // 开始日期的可选范围
      pickerOptionStart: {
        disabledDate: time => {
          if (this.form.endDate) {
            return time.getTime() > new Date(this.form.endDate).getTime();
          }
          return time.getTime() <= new Date();
        }
      },
      pickerOptionEnd: {
        disabledDate: time => {
          if (this.form.startDate) {
            return time.getTime() < new Date(this.form.startDate).getTime();
          }
          return time.getTime() <= new Date();
        }
      },
      options: provinceAndCityData
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    this.$nextTick(() => {
      this.getList();
      let formHeight = this.$refs.queryForm.$el.offsetHeight;
      console.log("formHeight", formHeight);
      this.height = `calc(100% - ${formHeight}px - 88px)`;
    }, 300);
    window.onresize = () => {
      let formHeight = this.$refs.queryForm.$el.offsetHeight;
      this.height = `calc(100% - ${formHeight}px - 88px)`;
    };
    this.userId = this.$store.state.user.name;
    let roles = this.$store.state.user.roles;
    if (
      roles.indexOf("common") != -1 ||
      roles.indexOf("accountant") != -1 ||
      roles.indexOf("cashier") != -1
    ) {
      this.isManager = false;
    } else {
      this.isManager = true;
    }
    if (this.$store.state.user.dept) {
      this.deptId = this.userId = this.$store.state.user.dept.deptId;
    }
  },
  methods: {
    /** 查询公车使用申请列表 */
    getList() {
      this.loading = true;
      listAdminCar(this.queryParams).then(response => {
        this.adminCarList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.isdisabled = false;
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        deptId: undefined,
        userId: undefined,
        busReason: undefined,
        busStartDate: undefined,
        busEndDate: undefined,
        useCount: undefined,
        useDistance: undefined,
        carType: undefined,
        attachment: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      };
      this.processInstanceId = undefined;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      if (
        this.queryParams.busDateList != null &&
        this.queryParams.busDateList.length > 0
      ) {
        this.queryParams.startDate =
          this.queryParams.busDateList[0] + " 00:00:00";
        this.queryParams.endDate =
          this.queryParams.busDateList[1] + " 23:59:59";
      }
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.busDateList = [];
      this.queryParams.startDate = undefined;
      this.queryParams.endDate = undefined;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      if (selection.length == 1) {
        if (
          selection[0].actBusinessStatus.status == "draft" ||
          selection[0].actBusinessStatus.status == "back" ||
          selection[0].actBusinessStatus.status == "cancel"
        ) {
        } else {
          this.single = true;
        }
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.flag = true;
      this.reset();
      this.open = true;
      this.title = "添加公车使用申请";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.flag = true;
      this.loading = true;
      this.reset();
      const id = row.id || this.ids;
      getAdminCar(id).then(response => {
        this.loading = false;
        this.form = response.data;
        if (response.data.actBusinessStatus.createTime) {
          this.form.numberNum =
            this.processKey +
            "@" +
            parseTime(
              response.data.actBusinessStatus.createTime,
              "{y}{m}{d}{h}{i}{s}"
            );
        }
        this.$nextTick(() => {
          this.processInstanceId =
            response.data.actBusinessStatus.processInstanceId;
        });
        this.open = true;
        this.title = "修改公车使用申请";
      });
    },
    //查看
    handleView(row) {
      this.flag = false;
      this.loading = true;
      this.reset();
      const id = row.id || this.ids;
      getAdminCar(id).then(response => {
        this.loading = false;
        this.form = response.data;
        if (response.data.actBusinessStatus.createTime) {
          this.form.numberNum =
            this.processKey +
            "@" +
            parseTime(
              response.data.actBusinessStatus.createTime,
              "{y}{m}{d}{h}{i}{s}"
            );
        }
        this.$nextTick(() => {
          this.processInstanceId =
            response.data.actBusinessStatus.processInstanceId;
        });
        this.isdisabled = true;
        this.open = true;
        this.title = "查看公车使用申请业务";
      });
    },
    /** 提交按钮 */
    submitForm(flag) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateAdminCar(this.form)
              .then(response => {
                this.$modal.msgSuccess("修改成功");
                if (flag === "submit") {
                  this.submitFormApply(response.data);
                } else {
                  this.open = false;
                }
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addAdminCar(this.form)
              .then(response => {
                this.$modal.msgSuccess("新增成功");
                if (flag === "submit") {
                  this.submitFormApply(response.data);
                } else {
                  this.open = false;
                  this.cancel();
                }
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    // 提交成功回调
    submitCallback() {
      this.open = false;
      this.getList();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除公车使用申请编号为"' + ids + '"的数据项？')
        .then(() => {
          this.loading = true;
          return delAdminCar(ids);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false;
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "oa/adminCar/export",
        {
          ...this.queryParams
        },
        `adminCar_${new Date().getTime()}.xlsx`
      );
    },
    //提交流程
    submitFormApply(entity) {
      //流程变量
      this.taskVariables = {
        entity: entity,
        isManager: this.isManager,
        deptId: this.deptId
      };
      const data = {
        processKey: this.processKey, // key
        businessKey: entity.id, // 业务id
        variables: this.taskVariables,
        classFullName: "com.ruoyi.oa.domain.OaAdminCar"
      };
      this.sendMessage = {
        title: "公车使用申请",
        messageContent: this.$store.state.user.nickName + "提交了公车使用审批"
      };
      // 启动流程
      processApi.startProcessApply(data).then(response => {
        this.taskId = response.data.taskId;
        this.$refs.verifyRef.visible = true;
        this.$refs.verifyRef.reset();
      });
    },
    //撤回
    cancelProcessApply(row) {
      this.$modal
        .confirm("是否撤销申请")
        .then(() => {
          this.loading = true;
          return processApi.cancelProcessApply(
            row.actBusinessStatus.processInstanceId
          );
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("撤回成功");
        })
        .finally(() => {
          this.loading = false;
        });
    },

    handleChangePlace1(arr) {
      this.form.useDistance = CodeToText[arr[0]] + "->" + CodeToText[arr[1]];
    },
    loadMap1() {
      this.form.useDistance = "";
    },
    /*日期范围控件选择完毕*/
    dateChanged() {
      if (this.form.busStartDate != null && this.form.busEndDate != null) {
        let val = dayjs(this.form.busEndDate).diff(
          dayjs(this.form.busStartDate),
          "days"
        );
        this.form.useCount = val < 0 ? val : val + 1;
      }
    }
  }
};
</script>
<style scoped>
.main {
  height: 100%;
}
/* 设置滚动条宽度和高度 */
::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  width: 8px; /* 横向滚动条 */
  height: 8px; /* 纵向滚动条 必写 */
}
/* 设置滚动条样式 */
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
  background-color: #dde;
  border-radius: 3px;
}
#selectForm >>> .el-form-item__label {
  font-size: 12px;
}
::v-deep .bjsm .el-form-item__content {
  width: calc(100% - 130px) !important;
}
</style>
